package com.c1.client.pan;

import com.c1.client.Frame;
import com.s.core.root.Ad;
import com.s.core.root.As;
import com.s.core.root.S;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zhangjiangnan
 */
@Getter
@Slf4j
public class Pans extends JPanel {

    private Pans() {
        setLayout(new CardLayout());
        Pan pan = new Pan(null, 0);
        add(StringUtils.EMPTY, pan.getFatherScrollPan());
    }

    private static volatile Pans me;

    public static Pans me() {
        if (me == null) {
            synchronized (Pans.class) {
                if (me == null) {
                    me = new Pans();
                }
            }
        }
        return me;
    }

    private int currentPanIndex = 0;

    public java.util.List<Pan> getPans() {
        return Arrays.stream(getComponents()).map(c -> {
            JScrollPane jScrollPane = (JScrollPane) c;
            return (Pan) jScrollPane.getViewport().getView();
        }).collect(Collectors.toList());
    }

    public Pan getCurrentPan() {
        java.util.List<Pan> panList = getPans();
        if (CollectionUtils.isEmpty(panList)) {
            return null;
        }
        return panList.get(currentPanIndex);
    }

    public void clear() {
        currentPanIndex = 0;
    }

    public void nextCard(boolean direction) {
        if (getCurrentPan() == null) {
            return;
        }
        if (direction) {
            currentPanIndex = (currentPanIndex + 1) % getPans().size();
        } else {
            currentPanIndex = currentPanIndex > 0 ? currentPanIndex - 1 : getPans().size() - 1;
        }
        ((CardLayout) getLayout()).show(this, getCurrentPan().code(false));
        Frame.me().setTitle(titleMessage());
    }

    public String titleMessage() {
        String code = getCurrentPan().code(false);
        String date = getCurrentPan().date(false);
        String titleMessage = "(" + getCurrentPan().getTitleNumberIndex() + "/" + getPans().size() + ")  ";
        titleMessage += date + "-";
        titleMessage += Ad.me().getBasicByCode(code).getName() + "-" + code;
        S s = As.me().get(code);
        if (s != null) {
            titleMessage += "-(自选:" + s.getP() + ")";
        }
        return titleMessage;
    }
}
